import { SET_LOGIN_FLAG, SET_USER_INFO } from '../types'
import UserApi from 'api/user'

const state = {
  login: localStorage.getItem('login') || false,
  userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
}

const actions = {

  /**
   * 用户登录
   * @param {object} commit
   * @param {object} loginParam
   */
  login ({ commit }, { username, password, rememberMe = false }) {
    UserApi.login(username, password, rememberMe).then(res => {
      localStorage.setItem('userInfo', JSON.stringify(res.data))
      localStorage.setItem('login', true)
      commit(SET_USER_INFO, res.data)
      commit(SET_LOGIN_FLAG, true)
      window.location.reload
    }).catch(() => {
      // ignore
      // console.log(error)
    })
  },

  // 用户注销
  logout ({commit}) {
    UserApi.logout().then(res => {
      localStorage.removeItem('userInfo')
      localStorage.removeItem('login')
      commit(SET_USER_INFO, {})
      commit(SET_LOGIN_FLAG, false)
    })
  }

  // setUserInfo ({commit}, usetInfo) {
  //   localStorage.setItem('userInfo', JSON.stringify(usetInfo))
  //   localStorage.setItem('login', true)
  //   commit(SET_USER_INFO, usetInfo)
  //   commit(SET_LOGIN_FLAG, true)
  // },

  // setIsLogin ({commit}, login) {
  //   commit(SET_LOGIN_FLAG, login)
  // }
}

const getters = {
  isLogin: state => state.login,
  getUserInfo: state => state.userInfo
}

const mutations = {
  [SET_USER_INFO] (state, userInfo) {
    state.userInfo = userInfo
  },
  [SET_LOGIN_FLAG] (state, login) {
    state.login = login
  }
}

export default {
  state,
  actions,
  getters,
  mutations
}
